<template>
  <div class="sales-amount-container">
    <div class="header">
      <h2>销售金额统计</h2>
      <div class="filter-group">
        <el-radio-group v-model="timeType" @change="handleTimeTypeChange">
          <el-radio label="day">当日</el-radio>
          <el-radio label="month">当月</el-radio>
          <el-radio label="year">当年</el-radio>
          <el-radio label="custom">自定义</el-radio>
        </el-radio-group>
        <el-date-picker
    v-if="timeType === 'custom'"
    v-model="dateRange"
    type="daterange"
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    value-format="YYYY-MM-DD"
    @change="handleDateRangeChange"
/>
</div>

</div>
<!-- 指标卡片 -->
<div class="stats-card-group">
<el-card class="stat-card">
  <div class="stat-info">
    <p class="stat-label">总销售额</p>
    <p class="stat-value">{{ totalSales.toFixed(2) }} 元</p>
    <p class="stat-change" :class="{ positive: salesChange >= 0, negative: salesChange < 0 }">
      {{ salesChange >= 0 ? '+' : '' }}{{ salesChange.toFixed(2) }}%
    </p>
  </div>
</el-card>

<el-card class="stat-card">
  <div class="stat-info">
    <p class="stat-label">订单数量</p>
    <p class="stat-value">{{ orderCount }}</p>
    <p class="stat-desc">笔订单</p>
  </div>
</el-card>

<el-card class="stat-card">
  <div class="stat-info">
    <p class="stat-label">平均客单价</p>
    <p class="stat-value">{{ avgOrderAmount.toFixed(2) }} 元</p>
  </div>
</el-card>
</div>

<!-- 销售额趋势 -->
<el-card class="chart-card">
<div class="chart-container">
  <h3>销售额趋势</h3>
  <div ref="chartRef" class="chart"></div>
</div>
</el-card>

<!-- 支付方式占比 -->
<el-card class="chart-card">
<div class="chart-container">
  <h3>支付方式占比</h3>
  <div ref="paymentChartRef" class="chart"></div>
</div>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import http from '@/axios/http'

/* -------------------------------- 类型定义 -------------------------------- */
interface StatsDTO {
  totalSales: number
  orderCount: number
  avgOrderAmount: number
  salesTrend: { date: string; amount: number }[]
  paymentRatio: { method: string; amount: number }[]
}

/* -------------------------------- 响应式状态 ------------------------------ */
const timeType = ref<'day' | 'month' | 'year' | 'custom'>('month')
const dateRange = ref<string[]>([]) // ['YYYY-MM-DD','YYYY-MM-DD']
const totalSales = ref(0)
const orderCount = ref(0)
const avgOrderAmount = ref(0)
const salesChange = ref(0) // 模拟环比

let salesChart: ECharts | null = null
let paymentChart: ECharts | null = null
const chartRef = ref<HTMLDivElement>()
const paymentChartRef = ref<HTMLDivElement>()

/* -------------------------------- 工具函数 ------------------------------- */
/** 根据时间粒度生成 [start,end] */
const calcDateRange = () => {
  const today = new Date()
  const yyyy = today.getFullYear()
  const mm = String(today.getMonth() + 1).padStart(2, '0')
  const dd = String(today.getDate()).padStart(2, '0')

  switch (timeType.value) {
    case 'day':
      return [`${yyyy}-${mm}-${dd}`, `${yyyy}-${mm}-${dd}`]
    case 'month':
      return [`${yyyy}-${mm}-01`, `${yyyy}-${mm}-${new Date(yyyy, today.getMonth() + 1, 0).getDate()}`]
    case 'year':
      return [`${yyyy}-01-01`, `${yyyy}-12-31`]
    case 'custom':
      return dateRange.value.length === 2 ? dateRange.value : []
    default:
      return []
  }
}

/* -------------------------------- API 调用 ------------------------------- */
const fetchStats = async () => {
  const range = calcDateRange()
  if (range.length !== 2) return

  try {
    const res = await http.post('/glsb/get_sales_stats', {
      startTime: range[0] + ' 00:00:00',
      endTime: range[1] + ' 23:59:59'
    })
    if (res.data.result !== 'success') throw new Error(res.data.msg || '接口异常')
    const data: StatsDTO = res.data.data
    totalSales.value = Number(data.totalSales || 0)
    orderCount.value = Number(data.orderCount || 0)
    avgOrderAmount.value = Number(data.avgOrderAmount || 0)
    salesChange.value = Math.random() * 20 - 5 // 仍模拟

    await nextTick()
    renderSalesTrend(data.salesTrend || [])
    renderPaymentPie(data.paymentRatio || [])
  } catch (e: any) {
    ElMessage.error(e.message || '获取统计数据失败')
  }
}

/* -------------------------------- 图表渲染 ------------------------------- */
const renderSalesTrend = (list: { date: string; amount: number }[]) => {
  if (!chartRef.value) return
  salesChart && salesChart.dispose()
  salesChart = echarts.init(chartRef.value)

  const times = list.map(i => i.date)
  const amounts = list.map(i => Number(i.amount))

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        const date = params[0].name
        const val = params[0].value
        window.dispatchEvent(new CustomEvent('sales-date-selected', { detail: { date, total: val } }))
        return `${date}<br/>销售额: ${val.toFixed(2)}元`
      }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: times, axisLabel: { rotate: 45 } },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} 元' } },
    series: [{ name: '销售额', type: 'bar', data: amounts, itemStyle: { color: '#409eff' } }]
  }
  salesChart.setOption(option)
}

const renderPaymentPie = (list: { method: string; amount: number }[]) => {
  if (!paymentChartRef.value) return
  paymentChart && paymentChart.dispose()
  paymentChart = echarts.init(paymentChartRef.value)

  const data = list.map(i => ({ name: i.method, value: Number(i.amount) }))
  const option: echarts.EChartsOption = {
    tooltip: { trigger: 'item' },
    legend: { orient: 'horizontal', bottom: 0 },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: ['40%', '70%'],
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } },
        labelLine: { show: false },
        data
      }
    ]
  }
  paymentChart.setOption(option)
}

/* -------------------------------- 事件处理 ------------------------------- */
const handleTimeTypeChange = () => {
  if (timeType.value !== 'custom') {
    dateRange.value = []
    fetchStats()
  }
}
const handleDateRangeChange = () => timeType.value === 'custom' && fetchStats()

/* -------------------------------- 生命周期 ------------------------------- */
onMounted(() => {
  fetchStats()
  window.addEventListener('resize', () => {
    salesChart?.resize()
    paymentChart?.resize()
  })
})
</script>
<style scoped>
/* 样式与原来完全一致，直接复用即可 */
.sales-amount-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.filter-group {
  display: flex;
  gap: 15px;
  align-items: center;
}
.stats-card-group {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
.stat-card {
  flex: 1;
  min-width: 200px;
}
.stat-info {
  text-align: center;
  padding: 15px 0;
}
.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}
.stat-change {
  font-size: 14px;
}
.positive {
  color: #4caf50;
}
.negative {
  color: #f56c6c;
}
.stat-desc {
  color: #606266;
  font-size: 14px;
}
.chart-card {
  margin-bottom: 20px;
}
.chart-container {
  padding: 15px;
}
.chart {
  width: 100%;
  height: 400px;
  margin-top: 15px;
}
</style>
